package com.chaoxing.controller;

import com.chaoxing.entity.Course;
import com.chaoxing.entity.SignResult;
import com.chaoxing.service.ChaoXingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/sign")
public class SignController {
    
    @Autowired
    private ChaoXingService chaoXingService;
    
    @GetMapping("/status")
    public Map<String, Object> getStatus() {
        Map<String, Object> result = new HashMap<>();
        result.put("loggedIn", chaoXingService.isLoggedIn());
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
    
    @PostMapping("/login")
    public Map<String, Object> login() {
        Map<String, Object> result = new HashMap<>();
        boolean success = chaoXingService.login();
        result.put("success", success);
        result.put("message", success ? "登录成功" : "登录失败");
        return result;
    }
    
    @GetMapping("/courses")
    public List<Course> getCourses() {
        if (!chaoXingService.isLoggedIn()) {
            chaoXingService.login();
        }
        return chaoXingService.getCourses();
    }
    
    @PostMapping("/manual/{courseId}/{clazzId}")
    public Map<String, Object> manualSign(@PathVariable String courseId, @PathVariable String clazzId) {
        Map<String, Object> result = new HashMap<>();
        
        if (!chaoXingService.isLoggedIn()) {
            result.put("success", false);
            result.put("message", "用户未登录");
            return result;
        }
        
        Course course = new Course();
        course.setCourseId(courseId);
        course.setClazzId(clazzId);
        
        List<com.chaoxing.entity.Activity> activities = chaoXingService.getActivities(course);
        
        if (activities.isEmpty()) {
            result.put("success", false);
            result.put("message", "未发现待签到的活动");
        } else {
            SignResult signResult = chaoXingService.doSign(activities.get(0), course);
            result.put("success", signResult.isSuccess());
            result.put("message", signResult.getMessage());
            result.put("data", signResult);
        }
        
        return result;
    }
}